package com.caigou.modules.query.viewmodel

import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.utils.Logger
import com.caigou.modules.query.bean.OpenPrizeTimeBean
import com.caigou.modules.query.repository.QueryRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @author #Suyghur.
 * Created on 2021/12/23
 */
@HiltViewModel
class PrizeDateViewModel @Inject constructor(private val repository: QueryRepository) : ViewModel() {

    val prizeDateLiveDate = MutableLiveData<Resource<MutableList<OpenPrizeTimeBean>>>()

    fun getPrizeDate() {
        prizeDateLiveDate.value = Resource.Loading()
        viewModelScope.launch {
            repository.getPrizeDate()
                .map {
                    if (it.code == 0) {
                        Resource.Success(it.data)
                    } else {
                        Resource.DataError(it.code, it.msg)
                    }
                }
                .catch {
                    val message = if (TextUtils.isEmpty(it.message)) {
                        ""
                    } else {
                        it.message!!
                    }
                    Resource.DataError<MutableList<OpenPrizeTimeBean>>(-1, message)
                    Logger.e("catch: ${it.message}")
                }
                .collectLatest {
                    prizeDateLiveDate.value = it
                }
        }
    }
}